<?php
/**
 *备货日志模型，主要用来记录备货过程的日志
 */
class Cron_Model_Backup_Log extends Model_Base {
	private $_backupLogData = [];
	//日志所属的商品及所在仓库
	private $_goodsSn;
	private $_warehouse;

	public function __construct($goodsSn, $warehouse) {
		$this->writeDb = $this->db("write_db");
		$this->_backupLogData = [];
		$this->_goodsSn = $goodsSn;
		$this->_warehouse = $warehouse;
	}

	/**
	 * 记录备货日志信息(此时未写入数据库，调用write方法时才会写入)
	 * @param  [type] $logFields      [description]
	 * @param  [type] $logFieldsValue [description]
	 * @return [type]                 [description]
	 */
	public function log($logFields, $logFieldsValue) {
		//日志备注字段拼接
		if (in_array($logFields, ['c_story_quantity_modify_remark', 'remark'])) {
			$beforeRemark = isset($this->_backupLogData[$logFields]) ? $this->_backupLogData[$logFields] . "\r\n" : "";
			$this->_backupLogData[$logFields] = $beforeRemark . $logFieldsValue;
		} else {
			$this->_backupLogData[$logFields] = $logFieldsValue;
		}
	}

	/**
	 * 记录备货日志持久化
	 * @param  [type] $goods_sn  [description]
	 * @param  [type] $warehouse [description]
	 * @param  array  $logData   [description]
	 * @param  [type] $date      [description]
	 * @return [type]            [description]
	 */
	public function write() {
		$date = date("Y-m-d");
		$logData = $this->_backupLogData;
		if (empty($logData)) {
			return $this->_error('记录的日志数据为空！');
		}

		$where = $this->writeDb->quoteInto("goods_sn=?", $this->_goodsSn);
		$where .= " AND " . $this->writeDb->quoteInto("warehouse=?", $this->_warehouse);
		$where .= " AND " . $this->writeDb->quoteInto("create_date=?", $date);

		$logHasData = $this->writeDb->fetchRow("select * from b_product_backup_log where $where");
		if (!$logHasData) {
			unset($logData['goods_sn'], $logData['warehouse'], $logData['date']);
			$logData['goods_sn'] = $this->_goodsSn;
			$logData['warehouse'] = $this->_warehouse;
			$logData['create_date'] = $date;

			return $this->writeDb->insert('b_product_backup_log', $logData);
		} else {
			if (isset($logData['remark'])) {
				$logData['remark'] .= $logHasData['remark'] . "\r\n";
			}
			return $this->writeDb->update('b_product_backup_log', $logData, $where);
		}
	}
}